package com.suns.client;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.suns.HelloServiceGrpc;
import com.suns.HelloServiceGrpc.HelloServiceFutureStub;
import com.suns.SimpleRequest;
import com.suns.SimpleResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * @author xiangminwen
 * @date 2024/4/3 11:13
 */
public class GrpcClient4 {

    public static void main(String[] args) throws Exception {
        //创建通信管道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        try {
            //获得Future代理对象Stub
            HelloServiceFutureStub serviceStub = HelloServiceGrpc.newFutureStub(channel);
            //组装参数
            SimpleRequest request = SimpleRequest.newBuilder().setName("client").setAge(10).addCode("code1").addCode("code2").build();

            //RPC调用获取响应
            ListenableFuture<SimpleResponse> response = serviceStub.hello(request);
            //异步回调获取
            Futures.addCallback(response, new FutureCallback<SimpleResponse>() {
                @Override
                public void onSuccess(@NullableDecl SimpleResponse res) {
                    System.out.println("异步响应:" + res.getData());
                }

                @Override
                public void onFailure(Throwable e) {
                }
            }, new ScheduledThreadPoolExecutor(1));

            //同步响应
            ListenableFuture<SimpleResponse> hello2 = serviceStub.hello(request);
            System.out.println("同步响应: " + hello2.get().getData());
            channel.awaitTermination(2, TimeUnit.SECONDS);
        } finally {
            if (!channel.isShutdown()) {
                channel.shutdown().awaitTermination(3, TimeUnit.SECONDS);
            }
        }
    }
}
